const Department = require('../models/department')
const { Op } = require('sequelize')
const { validateDepartment, validateDepartmentOrder } = require('../utils/validator')
const PermissionTemplate = require('../models/PermissionTemplate')
const logger = require('../utils/logger')
const sequelize = require('sequelize')
const logService = require('../services/logService')
const DepartmentPermission = require('../models/departmentPermission')
const PermissionService = require('../services/permissionService')
const DepartmentService = require('../services/departmentService')

// 创建部门
exports.create = async (req, res) => {
  try {
    const { error } = validateDepartment(req.body)
    if (error) {
      return res.status(400).json({
        code: 400,
        message: error.details[0].message
      })
    }

    // 如果有父部门，检查父部门是否存在
    if (req.body.parent_id) {
      const parentDepartment = await Department.findByPk(req.body.parent_id)
      if (!parentDepartment) {
        return res.status(400).json({
          code: 400,
          message: '父部门不存在'
        })
      }
    }

    // 如果设置了权限模板，检查模板是否存在
    if (req.body.template_id) {
      const template = await PermissionTemplate.findByPk(req.body.template_id)
      if (!template) {
        return res.status(400).json({
          code: 400,
          message: '权限模板不存在'
        })
      }
    }

    // 自动生成部门编码
    const code = await Department.generateCode(req.body.parent_id, req.body.source_type)
    
    const department = await Department.create({
      ...req.body,
      code
    })

    res.status(201).json({
      code: 200,
      message: '创建成功',
      data: department
    })
  } catch (error) {
    logger.error('Create department error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 更新部门
exports.update = async (req, res) => {
  try {
    const { id } = req.params
    const { error } = validateDepartment(req.body)
    if (error) {
      return res.status(400).json({
        code: 400,
        message: error.details[0].message
      })
    }

    const department = await Department.findByPk(id)
    if (!department) {
      return res.status(404).json({
        code: 404,
        message: '部门不存在'
      })
    }

    // 检查部门编码是否已被其他部门使用
    if (req.body.code !== department.code) {
      const existingDepartment = await Department.findOne({
        where: { 
          code: req.body.code,
          id: { [Op.ne]: id }
        }
      })
      if (existingDepartment) {
        return res.status(400).json({
          code: 400,
          message: '部门编码已存在'
        })
      }
    }

    // 如果有父部门，检查父部门是否存在且不是自己或自己的子部门
    if (req.body.parent_id) {
      if (req.body.parent_id === parseInt(id)) {
        return res.status(400).json({
          code: 400,
          message: '父部门不能是自己'
        })
      }

      const parentDepartment = await Department.findByPk(req.body.parent_id)
      if (!parentDepartment) {
        return res.status(400).json({
          code: 400,
          message: '父部门不存在'
        })
      }

      // TODO: 检查是否是自己的子部门
    }

    // 如果更改了权限模板，检查新模板是否存在
    if (req.body.template_id && req.body.template_id !== department.template_id) {
      const template = await PermissionTemplate.findByPk(req.body.template_id)
      if (!template) {
        return res.status(400).json({
          code: 400,
          message: '权限模板不存在'
        })
      }
    }

    await department.update(req.body)
    res.json({
      code: 200,
      message: '更新成功',
      data: department
    })
  } catch (error) {
    logger.error('Update department error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 删除部门
exports.delete = async (req, res) => {
  try {
    const { id } = req.params

    const department = await Department.findByPk(id)
    if (!department) {
      return res.status(404).json({
        code: 404,
        message: '部门不存在'
      })
    }

    // 检查是否有子部门
    const childCount = await Department.count({
      where: { parent_id: id }
    })
    if (childCount > 0) {
      return res.status(400).json({
        code: 400,
        message: '请先删除子部门'
      })
    }

    // TODO: 检查部门下是否有用户

    await department.destroy()
    res.json({
      code: 200,
      message: '删除成功'
    })
  } catch (error) {
    console.error('Delete department error:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    })
  }
}

// 获取部门详情
exports.getById = async (req, res) => {
  try {
    const { id } = req.params

    const department = await Department.findByPk(id, {
      include: [{
        model: PermissionTemplate,
        as: 'template',
        attributes: ['id', 'name', 'code', 'permissions']
      }]
    })
    
    if (!department) {
      return res.status(404).json({
        code: 404,
        message: '部门不存在'
      })
    }

    res.json({
      code: 200,
      data: department
    })
  } catch (error) {
    logger.error('Get department error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 获取部门树
exports.getTree = async (req, res) => {
  try {
    const tree = await DepartmentService.getDepartmentTree()
    
    res.json({
      code: 200,
      data: tree
    })
  } catch (error) {
    logger.error('Get department tree error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 更新部门排序
exports.updateOrder = async (req, res) => {
  try {
    const { error } = validateDepartmentOrder(req.body)
    if (error) {
      return res.status(400).json({
        code: 400,
        message: error.details[0].message
      })
    }

    const { orders } = req.body

    // 开启事务
    const transaction = await Department.sequelize.transaction()

    try {
      // 检查父部门是否存在
      for (const { parent_id } of orders) {
        if (parent_id !== null) {
          const parentDepartment = await Department.findByPk(parent_id)
          if (!parentDepartment) {
            await transaction.rollback()
            return res.status(400).json({
              code: 400,
              message: '父部门不存在'
            })
          }
        }
      }

      // 批量更新排序
      await Promise.all(
        orders.map(({ id, parent_id, order_num }) =>
          Department.update(
            { parent_id, order_num },
            { 
              where: { id },
              transaction
            }
          )
        )
      )

      await transaction.commit()

      res.json({
        code: 200,
        message: '更新成功'
      })
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  } catch (error) {
    logger.error('Update department order error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 获取权限模板列表
exports.getTemplates = async (req, res) => {
  try {
    const templates = await PermissionTemplate.findAll({
      where: { status: 1 },
      attributes: ['id', 'name', 'code', 'description', 'permissions'],
      order: [['id', 'ASC']]
    })

    res.json({
      code: 200,
      data: templates
    })
  } catch (error) {
    logger.error('Get templates error:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    })
  }
}

// 生成部门编码
exports.generateCode = async (req, res) => {
  try {
    const { parent_id } = req.query
    const code = await Department.generateCode(
      parent_id ? parseInt(parent_id) : null
    )
    
    res.json({
      code: 200,
      data: code
    })
  } catch (error) {
    logger.error('Generate department code error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 更新部门权限
exports.updatePermission = async (req, res) => {
  try {
    const { department_id, template_id, permissions } = req.body

    // 检查部门是否存在
    const department = await Department.findByPk(department_id)
    if (!department) {
      return res.status(404).json({
        code: 404,
        message: '部门不存在'
      })
    }

    // 检查权限模板是否存在
    const template = await PermissionTemplate.findByPk(template_id)
    if (!template) {
      return res.status(404).json({
        code: 404,
        message: '权限模板不存在'
      })
    }

    // 更新或创建部门权限
    const [departmentPermission] = await DepartmentPermission.upsert({
      department_id,
      template_id,
      permissions: permissions || template.permissions
    })

    // 清除部门及其所有用户的权限缓存
    await PermissionService.clearDepartmentPermissionCache(department_id)

    res.json({
      code: 200,
      message: '更新成功',
      data: departmentPermission
    })
  } catch (error) {
    logger.error('Update department permission error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

// 获取部门权限
exports.getPermission = async (req, res) => {
  try {
    const { department_id } = req.params

    const departmentPermission = await DepartmentPermission.findOne({
      where: { department_id },
      include: [{
        model: PermissionTemplate,
        as: 'template'
      }]
    })

    if (!departmentPermission) {
      return res.status(404).json({
        code: 404,
        message: '部门权限不存在'
      })
    }

    res.json({
      code: 200,
      data: departmentPermission
    })
  } catch (error) {
    logger.error('Get department permission error:', error)
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    })
  }
}

/**
 * 获取部门树
 */
exports.getDepartmentTree = async (req, res) => {
  try {
    const tree = await DepartmentService.getDepartmentTree()
    res.json({ success: true, data: tree })
  } catch (error) {
    logger.error('获取部门树失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

/**
 * 创建部门
 */
exports.createDepartment = async (req, res) => {
  try {
    const department = await DepartmentService.createDepartment(req.body)
    res.json({ success: true, data: department })
  } catch (error) {
    logger.error('创建部门失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

/**
 * 更新部门
 */
exports.updateDepartment = async (req, res) => {
  try {
    const { id } = req.params
    const department = await DepartmentService.updateDepartment(id, req.body)
    res.json({ success: true, data: department })
  } catch (error) {
    logger.error('更新部门失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

/**
 * 删除部门
 */
exports.deleteDepartment = async (req, res) => {
  try {
    const { id } = req.params
    await DepartmentService.deleteDepartment(id)
    res.json({ success: true })
  } catch (error) {
    logger.error('删除部门失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

/**
 * 更新部门父级
 */
exports.updateParent = async (req, res) => {
  try {
    const { id } = req.params
    const { parent_id } = req.body
    await DepartmentService.updateParent(id, parent_id)
    res.json({ success: true })
  } catch (error) {
    logger.error('更新部门父级失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

/**
 * 搜索部门
 */
exports.searchDepartments = async (req, res) => {
  try {
    const { keyword } = req.query
    const departments = await DepartmentService.searchDepartments(keyword)
    res.json({ success: true, data: departments })
  } catch (error) {
    logger.error('搜索部门失败:', error)
    res.status(500).json({ success: false, message: error.message })
  }
}

// 导出模块
module.exports = exports 